<template>
    <div>
         <!-- 面包屑导航区 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>系统管理</el-breadcrumb-item>
        <el-breadcrumb-item>班级列表</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
             <!-- 搜索 添加 -->
            <el-row :gutter="20">
                <el-col :span="10">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getClassesList">
                        <el-button type="success" slot="append" icon="el-icon-search" @click="getClassesList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="13">
                    <el-button type="primary" @click="showAddClassDialog" style="float:right">添加班级</el-button>
                </el-col>
            </el-row>
            <el-table :data="classList" border stripe :header-cell-style="table_header" empty-text="暂无数据">
                <!-- 索引列 -->
                <el-table-column type="index" label="序号" width="50px" align="center"></el-table-column>
                <el-table-column label="班级名称" prop="name" align="center"></el-table-column>
                <el-table-column label="专业" prop="major.name" align="center" min-width="150px"></el-table-column>
                <el-table-column label="年级" prop="grade.name" align="center"></el-table-column>
                <el-table-column label="辅导员" prop="counselor.nickname" align="center"></el-table-column>
                <el-table-column label="操作" width="300px" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditClassDialog(scope.row)">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeClassById(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分页区域 -->
        <div class="pager-box">
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pageNum"
                :page-sizes="[2, 5, 10, 15]"
                :page-size="queryInfo.pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                prev-text="上一页"
                next-text="下一页"
                :total="total"
                background
                hide-on-single-page
            ></el-pagination>
        </div>

        <!-- 编辑班级对话框 -->
        <el-dialog :title="Dialog_title" :visible.sync="ClassDialogVisible" width="40%" @close="resetForm('ClassFormRef')">
            <el-form
                :model="ClassForm"
                ref="ClassFormRef"
                :rules="ClassFormRules"
                label-width="100px"
            >
                <el-form-item label="班级名称" prop="Class_name">
                <el-input v-model="ClassForm.name"></el-input>
                </el-form-item>
                <el-form-item label="辅导员" prop="counselor_id">
                    <el-select v-model="ClassForm.counselor_id" filterable placeholder="请选择">
                        <el-option
                                v-for="item in userList"
                                :key="item.id"
                                :label="item.nickname"
                                :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="院系专业：">
                    <el-cascader
                        v-model="selectedKeys"
                        :options="parentMajorList"
                        :props="cascaderProps"
                        @change="parentMajorChanged"
                        clearable
                        filterable
                        style="width: 100%"
                    >
                    </el-cascader>
                </el-form-item>
                <el-form-item label="年级：">
                    <el-select v-model="ClassForm.grade_id" filterable placeholder="请选择">
                        <el-option
                        v-for="item in gradeList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="ClassDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="AddOrUpdateClass">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data () {
        return {
            queryInfo: {
                user_type: "",
                query: '',
                // 当前页数
                pageNum: 1,
                // 每页显示多少数据
                pageSize: 10,
            },
            total: 0,
            // 所有班级列表
            classList: [],
            gradeList: [],
            parentMajorList: [],
            userList: [],

            Dialog_state: "",
            Dialog_title: "",

            ClassDialogVisible: false,
            ClassForm: {},
            ClassFormRules: {
                name: [
                    { required: true, message: '请输入班级名称', trigger: 'blur' }
                ],
                counselor_id:[
                    { required: true, message: '请选择辅导员', trigger: 'blur' }
                ],
                major_id:[
                    { required: true, message: '请选择专业', trigger: 'blur' }
                ],
                grade_id:[
                    { required: true, message: '请选择年级', trigger: 'blur' }
                ],
            },
            selectedKeys: [],
            // 父级分类列表
            parentMajorList: [],
            // 指定级联选择器的配置对象
            cascaderProps: {
                // 配置触发选项 hover/click
                expandTrigger: 'hover',
                value: 'id',
                label: 'name',
                children: 'children',
            },
        }
    },
    created () {
        this.getClassesList();
        this.getAllDepartTree();
        this.getGradeList();
        this.getCounselorList();
    },
    methods: {
        table_header(row, column, rowIndex, columnIndex){
            return 'background-color: rgb(102,177,255);color: white;font-size:14px;'
        },
        // 监听 pagesize改变的事件
        handleSizeChange (newSize) {
            // console.log(newSize)
            this.queryInfo.pageSize = newSize
            this.getClassesList()
        },
        // 监听 页码值 改变事件
        handleCurrentChange (newSize) {
            // console.log(newSize)
            this.queryInfo.pageNum = newSize
            this.getClassesList()
        },
        // 添加分类 选择项发生变化触发
        parentMajorChanged () {
            // 如何selectKeys 数组的长度>0 说明选中父级分类
            if (this.selectedKeys.length > 0) {
                // 父级分类的Id
                this.ClassForm.major_id = this.selectedKeys[this.selectedKeys.length - 1]
            }
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.ClassForm = {};
            this.selectedKeys = [];
        },   
        async getClassesList() {
            const { data: res, status: status } = await this.axios.get('class/getClassList', {params: this.queryInfo})
            if (status !== 200) {
                return this.$message.error('获取班级列表失败！')
            }
            this.classList = res.data.classes;
            this.queryInfo.total = res.data.total;
        },
        async getCounselorList(){
            this.queryInfo.user_type = "counselor";
            const {data: res, status: status} = await this.axios.get('users/getUserList', {params: this.queryInfo});
            if (status !== 200) return this.$message.error("获取辅导员列表失败");
            this.userList = res.data.users;
        },
        async getGradeList(){
            const { data: res, status: status } = await this.axios.get("grade/getGradeList")
            if (status !== 200) {
                return this.$message.error('获取院系列表失败！')
            }
            this.gradeList = res.data.grades;
        },
        async getAllDepartTree(){
            const { data: res, status: status } = await this.axios.get('department/getAllDepartmentTree')
            if (status !== 200) {
                return this.$message.error('获取部门列表树失败！')
            }
            this.parentMajorList = res.data;
        },

        showAddClassDialog(){
            this.Dialog_state = "add";
            this.Dialog_title = "添加班级";
            this.ClassDialogVisible = true
        },
        // 编辑班级
        async showEditClassDialog (Class) {
            this.Dialog_state = 'edit';
            this.Dialog_title = "编辑班级";
            this.ClassForm = Class;
            const { data: res, status: status } = await this.axios.get('class/getClassMajorList', {params:{"id":Class.major_id}});
            if (status !== 200) {
                return this.$message.error('获取部门列表树失败！')
            }
            this.selectedKeys = res.data;
            this.ClassDialogVisible = true
        },
        // 添加班级A
        AddOrUpdateClass () {
            var class_form = JSON.parse(JSON.stringify(this.ClassForm));
            class_form.counselor = {};
            class_form.grade = {};
            class_form.major = {};
            if (this.Dialog_state === "add") {
                this.$refs.ClassFormRef.validate(async valid => {
                    if (!valid) return
                    const {data: res, status: status} = await this.axios.post('class/addClass', class_form);
                    if (status !== 201) {
                        this.$message.error('添加班级失败！')
                    }
                    this.$message.success('添加班级成功！');
                    this.AddClassDialogVisible = false;
                    this.getClassesList()
                })
            }else {
                this.$refs.ClassFormRef.validate(async valid => {
                    if (!valid) return
                    const { data: res, status: status } = await this.axios.put('class/updateClass', class_form);
                    if (status !== 200) {
                        this.$message.error('更新班级信息失败！')
                    }
                    // 隐藏编辑班级对话框
                    this.editClassDialogVisible = false;
                    this.$message.success('更新班级信息成功！');
                    this.getClassesList()
                })
            }
            this.ClassDialogVisible = false
        },
        // 删除班级
        async removeClassById (Class) {
            const confirmResult = await this.$confirm(
                '此操作将永久删除班级 ' + Class.name +  ',  是否继续?',
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            ).catch(err => err);
            if (confirmResult !== 'confirm') {
                return this.$message.info('已取消删除')
            }
            const { data: res, status: status } = await this.axios.delete('class/deleteClass', {params: {"id": Class.id}});
            if (status !== 200) return this.$message.error('删除班级失败！')
            this.$message.success('删除班级成功！')
            this.getClassesList()
        },

    } 
}
</script>
<style lang="less" scoped>

</style>